import axios, { type AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

/**
 * 发送支持流式响应的HTTP请求
 * 专门用于处理Spring AI的流式响应
 * @param config Axios请求配置
 * @returns 返回ReadableStream
 */
export async function streamHttp(config: AxiosRequestConfig): Promise<ReadableStream> {
  // 从localStorage或sessionStorage获取token
  let token = ''
  try {
    const authData = localStorage.getItem('auth')
    if (authData) {
      const parsedData = JSON.parse(authData)
      token = parsedData.state?.token || parsedData.token || ''
    }
  } catch (error) {
    console.error('从localStorage获取token失败', error)
  }

  if (!token) {
    try {
      const authData = sessionStorage.getItem('auth')
      if (authData) {
        const parsedData = JSON.parse(authData)
        token = parsedData.state?.token || parsedData.token || ''
      }
    } catch (error) {
      console.error('从sessionStorage获取token失败', error)
    }
  }

  // 设置请求头
  const headers: Record<string, string> = {
    'Accept': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  }

  // 如果有token，添加到请求头
  if (token) {
    headers['Authorization'] = token
  }

  // 如果是POST或PUT请求，设置Content-Type
  if (config.method?.toUpperCase() === 'POST' || config.method?.toUpperCase() === 'PUT') {
    if (!config.headers?.['Content-Type']) {
      headers['Content-Type'] = 'application/json'
    }
  }

  // 合并headers
  config.headers = { ...headers, ...config.headers }

  try {
    // 使用fetch API发送请求，支持流式响应
    let url = config.url || ''

    // 处理GET请求的查询参数
    if (config.method?.toUpperCase() === 'GET' && config.params) {
      const queryParams = new URLSearchParams()
      for (const key in config.params) {
        if (config.params[key] !== undefined && config.params[key] !== null) {
          queryParams.append(key, config.params[key])
        }
      }

      // 将查询参数添加到URL
      const queryString = queryParams.toString()
      if (queryString) {
        url += (url.includes('?') ? '&' : '?') + queryString
      }
    }

    const response = await fetch(url, {
      method: config.method || 'GET',
      headers: config.headers as HeadersInit,
      body: (config.method?.toUpperCase() !== 'GET' && config.data) ? JSON.stringify(config.data) : undefined,
      credentials: 'include' // 包含跨域cookie
    })

    if (!response.ok) {
      // 处理错误响应
      const errorText = await response.text()
      throw new Error(`请求失败: ${response.status} ${errorText || response.statusText}`)
    }

    // 返回可读流
    return response.body as ReadableStream
  } catch (error: any) {
    // 处理网络错误
    if (error.message.includes('Network Error')) {
      ElMessage.error('网络连接失败，请检查您的网络连接或服务器是否正常运行')
    } else {
      ElMessage.error(error.message || '发生未知错误')
    }
    throw error
  }
}
